package com.dh.example.io.configuration;

import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
import com.dh.example.io.handler.HeartBeatHandler;
import com.dh.example.io.listener.AuthorizationListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 套接字io配置
 *
 * @author yolo
 * @date 2024/03/06 19:07:02
 */
@Configuration
@Slf4j
public class SocketIoConfig {

    @Value("${netty.socket.port}")
    private int port;


    @Resource
    private AuthorizationListener authorizationListener;


    /**
     * 创建socketIOServer实例
     *
     * @return {@code SocketIOServer}
     */
    @Bean
    public SocketIOServer socketIoServer() throws UnknownHostException {
        com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
        config.setHostname(InetAddress.getLocalHost().getHostAddress());
        config.setPort(port);
        // 设置心跳间隔为5秒
        config.setPingInterval(5000);
        // 设置心跳超时时间为10秒
        config.setPingTimeout(10000);

        // 安全校验 设置socket-io client连接时的安全校验
        config.setAuthorizationListener(authorizationListener::isAuthorized);
        SocketIOServer socketIoServer = new SocketIOServer(config);
        socketIoServer.addListeners(new HeartBeatHandler());
        return socketIoServer;
    }

    /**
     * 开启netty socket-io的注解功能
     *
     * @param socketServer 套接字服务器
     * @return {@code SpringAnnotationScanner}
     */
    @Bean
    public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) {
        return new SpringAnnotationScanner(socketServer);
    }
}
